package com.hyt.it.ogt.controller.pj;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.it.ogt.controller.base.BaseController;
import com.hyt.it.ogt.pj.common.Constants;
import com.hyt.it.ogt.pj.common.MarkException;
import com.hyt.it.ogt.pj.common.ResponseCode;
import com.hyt.it.ogt.pj.enums.ProjectDownLoadStatusEnum;
import com.hyt.it.ogt.pj.model.entity.Paper;
import com.hyt.it.ogt.pj.model.entity.Project;
import com.hyt.it.ogt.pj.model.vo.PaperItemVo;
import com.hyt.it.ogt.pj.model.vo.ProjectVo;
import com.hyt.it.ogt.pj.service.IPaperService;
import com.hyt.it.ogt.pj.service.IProjectDataDownLoadService;
import com.hyt.it.ogt.pj.service.IProjectService;
import com.hyt.loginfo.model.User;
import com.hyt.loginfo.service.IBaseLoginService;
import com.hyt.model.PageParam;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评卷项目表 前端控制器
 * </p>
 *
 * @author qiaozj
 * @since 2020-07-09
 */
@ApiSort(value = 1)
@Api(tags = "1.评卷项目接口", value = "评卷项目接口")
@RestController
@RequestMapping("/project")
@Slf4j
public class ProjectController extends BaseController {

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IBaseLoginService baseLoginService;

    @Autowired
    private IProjectDataDownLoadService projectDataDownLoadService;

    @Autowired
    private IPaperService paperService;


    @ApiOperationSort(value = 1)
    @ApiOperation(value = "1.1.1根据id查询项目", notes = Constants.SWAGGER_METHOD_NOTES)
    @GetMapping("query/{id}")
    public Object query(@PathVariable("id") String id) {
        Project project = projectService.getById(id);
        return ApiResponse.builder().code(ResponseCode.SUCCESS).data(project).build();
    }


    @ApiOperationSort(value = 2)
    @ApiOperation(value = "1.1.2从考务获取考试任务", notes = "20000:获取任务成功")
    @GetMapping("getPage")
    public Object getPage(@RequestParam("projectName") String projectName, @RequestParam("markStatus") String markStatus, @RequestParam("current") long current, @RequestParam("size") long size) {
        PageParam<ProjectVo> projectVos = projectService.getPageProject(projectName, markStatus, current, size);
        return ApiResponse.builder().code(ResponseCode.SUCCESS).data(projectVos).build();
    }

    @ApiOperationSort(value = 10)
    @ApiOperation(value = "1.2.1添加项目", notes = Constants.SWAGGER_METHOD_NOTES)
    @PostMapping("add")
    public Object add(@RequestBody Project project) {
        boolean flag = projectService.save(project);
        if (flag) {
            return ApiResponse.builder().code(ResponseCode.SUCCESS).build();
        } else {
            return ApiResponse.builder().code(ResponseCode.ERROR).build();
        }
    }

    @ApiOperationSort(value = 20)
    @ApiOperation(value = "1.3.1更新项目", notes = Constants.SWAGGER_METHOD_NOTES)
    @PutMapping("update")
    public Object update(@RequestBody Project project) {
        boolean flag = projectService.updateById(project);
        if (flag) {
            return ApiResponse.builder().code(ResponseCode.SUCCESS).build();
        } else {
            return ApiResponse.builder().code(ResponseCode.ERROR).build();
        }
    }

    @ApiOperationSort(value = 21)
    @ApiOperation(value = "1.3.2初始化项目", notes = "20002:传入项目id为空;")
    @GetMapping("initProject/{id}")
    public Object initProject(@PathVariable("id") String id) throws Exception {
        try {
            String userId = getUserId();
            projectService.initProject(id, userId);
            return ApiResponse.builder()
                    .code(ResponseCode.SUCCESS)
                    .build();
        } catch (MarkException e) {
            logger.error("评卷初始化失败:" + e.getMessage());
            return ApiResponse.builder().code(Integer.parseInt(e.getMessage())).build();
        } catch (Exception e) {
            logger.error("评卷初始化失败:" + e.getMessage());
            return ApiResponse.builder().code(ResponseCode.ERROR).build();
        }
    }

    @ApiOperationSort(value = 21)
    @ApiOperation(value = "1.3.2增量添加考生数量", notes = Constants.SWAGGER_METHOD_NOTES)
    @GetMapping("addProjectStudent/{id}")
    public Object addProjectStudent(@PathVariable("id") String id) throws Exception {
        try {
            String userId = getUserId();
            projectService.addProjectStudent(id, userId);
            return ApiResponse.builder()
                    .code(ResponseCode.SUCCESS)
                    .build();
        } catch (MarkException e) {
            logger.error("获取增量评卷任务:" + e.getMessage());
            return ApiResponse.builder().code(Integer.parseInt(e.getMessage())).build();
        } catch (Exception e) {
            logger.error("获取增量评卷任务:" + e.getMessage());
            return ApiResponse.builder().code(ResponseCode.ERROR).build();
        }
    }

    @ApiOperationSort(value = 30)
    @ApiOperation(value = "1.4.1根据id删除项目", notes = Constants.SWAGGER_METHOD_NOTES)
    @DeleteMapping("delete/{id}")
    public Object delete(@PathVariable("id") String id) {
        boolean flag = projectService.removeById(id);
        if (flag) {
            return ApiResponse.builder().code(ResponseCode.SUCCESS).build();
        } else {
            return ApiResponse.builder().code(ResponseCode.ERROR).build();
        }
    }

    @ApiOperationSort(value = 31)
    @ApiOperation(value = "1.4.2 查询评卷项目分页数据", notes = "20000:成功; 20404:失败", response = ProjectVo.class)
    @GetMapping("page")
    public Object page(PageParam<ProjectVo> pageParam, String projectName, String markStatus) {
        log.debug("# 查询评卷项目分页数据参数 ： {} {}", projectName, markStatus);
        try {
            String officeId = getOfficeId();
            Page<ProjectVo> page = projectService.page(pageParam, projectName, markStatus, officeId);
            return ApiResponse.builder()
                    .code(ResponseCode.SUCCESS)
                    .data(page)
                    .build();
        } catch (Exception e) {
            log.error("# 查询评卷项目分页数据异常:", e);
            return ApiResponse.builder()
                    .code(ResponseCode.QUERY_PROJECT_PAGE_FAIL)
                    .build();
        }
    }


    @ApiOperationSort(value = 9)
    @ApiOperation(value = "1.5.1 项目数据下载", notes = "20000:成功, 51150101:获取不到当前登录人信息,51150102:下载文件失败,51150103:文件生成中请耐心等待")
    @GetMapping("projectDataDownload")
    @PreAuthorize("hasAuthority('gl_pj_listdownpj')")
    public ApiResponse<String> projectDataDownload(@RequestParam String projectId, HttpServletResponse response) throws Exception {
        log.info("# 项目数据下载参数 ： {}", projectId);
        User user = baseLoginService.getSysUser();
        if (null == user || StringUtils.isEmpty(user.getId())) {
            return ApiResponse.<String>builder()
                    .code(51150101)
                    .build();
        }
        String fileUrl = projectService.projectDataDownload(projectId, user.getOfficeid(), user.getId(), getDeptId());

        if (StringUtils.isNotEmpty(fileUrl)) {
            if (ProjectDownLoadStatusEnum.downloading.getStatus().equals(fileUrl)) {
                return ApiResponse.<String>builder().code(51150103).data(null).build();
            } else if (ProjectDownLoadStatusEnum.fail.getStatus().equals(fileUrl)) {
                return ApiResponse.<String>builder().code(51150102).data(null).build();
            } else {
                return ApiResponse.<String>builder().code(ResponseCode.SUCCESS).data(fileUrl).build();
            }
        } else {
            return ApiResponse.<String>builder().code(51150103).data(null).build();
        }
    }


    @ApiOperation(value = "1.5.2 获取项目下是否存在主观评分题", notes = "20000:成功, 51150201:获取不到当前登录人信息")
    @ApiOperationSort(value = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "projectId", value = "评卷项目ID", dataType = "string", paramType = "query", required = true
            )
    })
    @PostMapping("getSubjectivePaperItems")
    public Object getSubjectivePaperItemTree(@RequestParam String projectId) throws Exception {
        log.info("# 项目数据下载参数:{}", projectId);
        User user = baseLoginService.getSysUser();
        if (null == user) {
            return ApiResponse.builder()
                    .code(51150101)
                    .build();
        }
        List<PaperItemVo> paperItemVos = new ArrayList<PaperItemVo>();
        List<Paper> papers = paperService.selectByProject(projectId);
        if (CollectionUtils.isNotEmpty(papers)) {
            for (Paper paper : papers) {
                List<PaperItemVo> paperItemVosTemp = projectDataDownLoadService.getSubjectivePaperItemTree(paper.getId());
                paperItemVos.addAll(paperItemVosTemp);
            }
        }
        return ApiResponse.builder()
                .code(ResponseCode.SUCCESS).data(paperItemVos)
                .build();
    }

    @ApiOperationSort(value = 10)
    @ApiOperation(value = "1.5.3 客观题成绩数据下载", notes = "20000:成功, 51150301:获取不到当前登录人信息, 51150302:下载文件失败, 51150303:文件生成中请耐心等待")
    @GetMapping("objectiveScoreDataDownload")
    @PreAuthorize("hasAuthority('gl_pj_listdownogcj')")
    public ApiResponse<?> objectiveScoreScoreDataDownload(@RequestParam String projectId, HttpServletResponse response) throws Exception {
        log.info("# 客观题成绩数据下载 ： {}", projectId);
        User user = baseLoginService.getSysUser();
        if (null == user || StringUtils.isEmpty(user.getId())) {
            return ApiResponse.builder()
                    .code(51150301)
                    .build();
        }
        String fileUrl = projectService.objectiveScoreDataDownload(projectId, user.getOfficeid(), user.getId(), getDeptId(), response);
        if (StringUtils.isNotEmpty(fileUrl)) {
            if (ProjectDownLoadStatusEnum.downloading.getStatus().equals(fileUrl)) {
                return ApiResponse.builder().code(51150103).data(null).build();
            } else if (ProjectDownLoadStatusEnum.fail.getStatus().equals(fileUrl)) {
                return ApiResponse.<String>builder().code(51150302).data(null).build();
            } else {
                return ApiResponse.builder().code(ResponseCode.SUCCESS).data(fileUrl).build();
            }
        } else {
            return ApiResponse.builder().code(51150302).data(null).build();
        }
    }


    @ApiOperationSort(value = 71)
    @ApiOperation(value = "1.7.1 查询评卷项目的评卷状态", notes = "20000:成功; 51160101:获取项目信息失败", response = ProjectVo.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "projectId", value = "项目id", dataType = "string", paramType = "query", required = true)
            }
    )
    @GetMapping("getProjectMarkStatusByProjectId")
    public ApiResponse<?> getProjectMarkStatusByProjectId(@RequestParam String projectId) {
        log.debug("# 查询评卷项目的评卷状态参数:{}", projectId);
        try {
            String officeId = getOfficeId();
            ProjectVo projectVo = projectService.getProjectMarkStatusByProjectId(projectId, officeId);
            if (null == projectVo) {
                return ApiResponse.builder()
                        .code(51160101)
                        .build();
            }
            return ApiResponse.builder()
                    .code(ResponseCode.SUCCESS)
                    .data(projectVo)
                    .build();
        } catch (Exception e) {
            log.error("# 查询评卷项目的评卷状态异常:", e);
            return ApiResponse.builder()
                    .code(51160101)
                    .build();
        }
    }


    @ApiOperation(value = "1.8.1 获取试卷下面所有的客观题列表", notes = "20000:成功, 51180101:获取不到当前登录人信息")
    @ApiOperationSort(value = 81)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "paperId", value = "试卷ID", dataType = "string", paramType = "query", required = true
            )
    })
    @PostMapping("getPaperSubjectivePaperItems")
    public Object getPaperSubjectivePaperItemTree(@RequestParam String paperId) throws Exception {
        log.info("# 项目数据下载参数:{}", paperId);
        User user = baseLoginService.getSysUser();
        if (null == user) {
            return ApiResponse.builder()
                    .code(51150101)
                    .build();
        }
        List<PaperItemVo> paperItemVosTemp = projectDataDownLoadService.getSubjectivePaperItemTree(paperId);
        return ApiResponse.builder()
                .code(ResponseCode.SUCCESS).data(paperItemVosTemp)
                .build();
    }


    @ApiOperation(value = "1.9.1 大考版项目数据下载", notes = "20000:成功, 51150101:获取不到当前登录人信息,51150102:下载文件失败,51150103:文件生成中请耐心等待")
    @ApiOperationSort(value = 91)
    @GetMapping("dkbProjectDataDownload")
    @PreAuthorize("hasAuthority('gl_pj_downdkbpj')")
    public ApiResponse<String> dkbProjectDataDownload(@RequestParam String projectId, HttpServletResponse response) throws Exception {
        log.info("# 大考版项目数据下载参数 ： {}", projectId);
        User user = baseLoginService.getSysUser();
        if (null == user || StringUtils.isEmpty(user.getId())) {
            return ApiResponse.<String>builder()
                    .code(51150101)
                    .build();
        }
        String fileUrl = projectService.dkbProjectDataDownload(projectId, user.getOfficeid(), user.getId(), getDeptId());

        if (StringUtils.isNotEmpty(fileUrl)) {
            if (ProjectDownLoadStatusEnum.downloading.getStatus().equals(fileUrl)) {
                return ApiResponse.<String>builder().code(51150103).data(null).build();
            } else if (ProjectDownLoadStatusEnum.fail.getStatus().equals(fileUrl)) {
                return ApiResponse.<String>builder().code(51150102).data(null).build();
            } else {
                return ApiResponse.<String>builder().code(ResponseCode.SUCCESS).data(fileUrl).build();
            }
        } else {
            return ApiResponse.<String>builder().code(51150103).data(null).build();
        }
    }


    @ApiOperation(value = "1.9.2 客观题成绩数据下载", notes = "20000:成功, 51150301:获取不到当前登录人信息, 51150302:下载文件失败, 51150303:文件生成中请耐心等待")
    @ApiOperationSort(value = 92)
    @GetMapping("dkbObjectiveScoreDataDownload")
    @PreAuthorize("hasAuthority('gl_pj_dkbcgcj')")
    public ApiResponse<?> dkbObjectiveScoreDataDownload(@RequestParam String projectId, HttpServletResponse response) throws Exception {
        log.info("# 大考版客观题成绩数据下载 ： {}", projectId);
        User user = baseLoginService.getSysUser();
        if (null == user || StringUtils.isEmpty(user.getId())) {
            return ApiResponse.builder()
                    .code(51150301)
                    .build();
        }
        String fileUrl = projectService.dkbObjectiveScoreDataDownload(projectId, user.getOfficeid(), user.getId(), getDeptId(), response);
        if (StringUtils.isNotEmpty(fileUrl)) {
            if (ProjectDownLoadStatusEnum.downloading.getStatus().equals(fileUrl)) {
                return ApiResponse.builder().code(51150103).data(null).build();
            } else if (ProjectDownLoadStatusEnum.fail.getStatus().equals(fileUrl)) {
                return ApiResponse.<String>builder().code(51150302).data(null).build();
            } else {
                return ApiResponse.builder().code(ResponseCode.SUCCESS).data(fileUrl).build();
            }
        } else {
            return ApiResponse.builder().code(51150302).data(null).build();
        }
    }

}
